import React from 'react';
import styles from './index.less';
import { connect } from 'umi';
import _ from 'lodash';
import moment from 'moment';

import { TRDefault, TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts.js';

import { PageLoading } from '@/components';
import { useExcel } from '@/hooks';
import { useTRState } from '@/pages/ETrade/components';
import { weekColumns } from '@/pages/GanSuDaTang/ProvinceSpotsReplay/helper';
import { getGansuStations } from '@/pages/GanSuDaTang/services';

import { HeaderSearch } from './components/headerSearch';
import { DayContent } from './components/DayContent/index.jsx';
import { WeekContent } from './components/weekContent';
import { MonthContent } from './components/monthContent';
import { getDataList, getMonthDataList, getWeekDataList } from './services';
import { getFlagDataSource } from './utils';

const MyComponent = ({ menuCode, buttonPermissions }) => {
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((x) => x.menuCode === 'GanSuProvinceSpotsReplay'),
    error: '',
    dataHeader: [],
    dataSource: [],
    pieData: {},
    stations: [],
    spinning: true, // form
    loading: true,
    date: '',
    queryForm: {},
  });

  React.useEffect(() => {
    fetchPower().then();
  }, []);

  /** methods */
  const fetchPower = async () => {
    // 数据权限
    const { error, stations } = await getGansuStations(menuCode);
    setState({
      error,
      stations,
      spinning: false,
    });
  };

  const getSearchTime = (v = null, searchType) => {
    let searchDate = [moment(), moment()];
    switch (searchType) {
      case 0:
        searchDate = v;
        break;
      case 1:
        searchDate = [moment(v).weekday(0), moment(v).weekday(6)];
        break;
      case 2:
        searchDate = [moment(v).startOf('months'), moment(v).endOf('months')];
    }
    return searchDate;
  };

  const getAnalysisParams = () => {
    const searchDate = getSearchTime(state.queryForm.date, state.queryForm.searchType);
    return {
      startDate: searchDate[0].format('YYYY-MM-DD'),
      endDate: searchDate[1].format('YYYY-MM-DD'),
      stationIds: state.queryForm.stationIdList,
    };
  };

  const fetchData = async (values) => {
    setState({
      queryForm: values,
    });
    const searchDate = getSearchTime(values.date, values.searchType);

    let sever = false;
    let params = {};
    switch (values.searchType) {
      case 0:
        // 日报
        sever = getDataList;
        params = {
          startDate: searchDate[0].format('YYYY-MM-DD'),
          endDate: searchDate[1].format('YYYY-MM-DD'),
          stationIds: values.stationIdList,
          tableList: values.columnsType,
        };
        break;
      case 1:
        sever = getWeekDataList;
        params = {
          startDate: searchDate[0].format('YYYY-MM-DD'),
          endDate: searchDate[1].format('YYYY-MM-DD'),
          stationIdList: values.stationIdList,
        };
        break;
      case 2:
        sever = getMonthDataList;
        params = {
          startDate: searchDate[0].format('YYYY-MM-DD'),
          endDate: searchDate[1].format('YYYY-MM-DD'),
          stationIds: values.stationIdList,
        };
        break;
    }
    if (sever) {
      setState({
        loading: true,
      });
      const res = await sever(params);
      if (res?.statusCode !== HttpCode.SUCCESS) {
        setState({
          error: true,
        });
      }
      const dataSource = _.isArray(res.data)
        ? res.data
        : getFlagDataSource(res.data?.tableData) || [];
      const dataHeader = res?.data?.tableHead || [];
      let pieData = {};
      // 当为交易月报时多拿饼状图的参数
      if (values.searchType === 2) {
        pieData = res?.data?.monthIncome || {};
        const hydroPowerIncome = isNaN(Number(pieData.hydroPowerIncome))
          ? 0
          : Number(pieData.hydroPowerIncome);
        const windPowerIncome = isNaN(Number(pieData.windPowerIncome))
          ? 0
          : Number(pieData.windPowerIncome);
        const photoVoltaicIncome = isNaN(Number(pieData.photoVoltaicIncome))
          ? 0
          : Number(pieData.photoVoltaicIncome);
        const total = hydroPowerIncome + windPowerIncome + photoVoltaicIncome;
        pieData = {
          hydroPowerIncome,
          windPowerIncome,
          photoVoltaicIncome,
          total,
        };
      }
      setState({
        dataSource,
        dataHeader,
        pieData,
        loading: false,
      });
    }
  };

  const buildColumns = (arr) => {
    let columns = [];
    arr.map((i) => {
      if (i.parentName && columns.filter((d) => d.name === i.parentName).length === 0) {
        columns.push({ name: i.parentName, children: [] });
      }
      columns.map((d) => {
        if (d.name === i.parentName) {
          d.children.push({ ...i, code: i.field });
        }
      });
    });
    columns.unshift({ name: '交易单元', code: 'name' });
    return columns;
  };

  const buildData = (arr) => {
    let data = [];
    const build = (list) => {
      list.forEach((i) => {
        data.push({ ...i.data, name: i.name });
        if (_.isArray(i.children)) {
          build(i.children);
        }
      });
    };
    build(arr);
    return data;
  };

  const onExport = () => {
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    if (state.queryForm.searchType === 0 || state.queryForm.searchType === 2) {
      const columns = buildColumns(state.dataHeader);
      const dataSource = buildData(state.dataSource);
      useExcel({
        data: dataSource,
        columns: columns,
        filename: state.queryForm.searchType === 0 ? '交易日报' : '交易月报',
      });
    } else if (state.queryForm.searchType === 1) {
      const columns = weekColumns.map((i) => ({
        ...i,
        name: i.name
          ? i.name.props.children[0] + i.name.props.children[1]['props']['children']
          : '',
      }));
      useExcel({
        data: state.dataSource,
        columns: columns,
        filename: '交易周报',
      });
    }
  };

  const _getContent = () => {
    switch (state.queryForm.searchType) {
      case 0:
        return (
          <DayContent
            loading={state.loading}
            dataSource={state.dataSource}
            dataHeader={state.dataHeader}
            buttonPermissions={buttonPermissions}
            menuCode={menuCode}
            stations={state.stations}
            queryForm={state.queryForm}
            fetchData={fetchData}
          />
        );
      case 1:
        return (
          <WeekContent
            loading={state.loading}
            dataSource={state.dataSource}
            getAnalysisParams={getAnalysisParams}
          />
        );
      case 2:
        return (
          <MonthContent
            pieData={state.pieData}
            loading={state.loading}
            dataSource={state.dataSource}
            dataHeader={state.dataHeader}
          />
        );
    }
  };

  /** render */
  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.stations?.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.page}>
      <div className={styles.head}>
        <HeaderSearch stations={state.stations} onExport={onExport} fetchData={fetchData} />
      </div>
      <div className={styles.main}>{_getContent()}</div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(MyComponent);
